package ldh.im.fxbase.service;

import ldh.im.dto.business.base.FeedbackCreateReq;
import ldh.im.dto.business.item.FeedbackItem;
import ldh.im.fxbase.dao.ImFeedbackDao;
import ldh.im.fxbase.dao.ImMessageDao;
import ldh.im.fxbase.data.pojo.ImFeedback;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.MessageExt;
import ldh.im.fxbase.data.pojo.status.ImFeedbackStatus;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.util.ConfigUtil;
import ldh.im.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

public class FeedbackService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FeedbackService.class);

    private ImFeedbackDao feedbackDao = BeanFactory.getInstance().getBean(ImFeedbackDao.class);
    private ImMessageDao messageDao = BeanFactory.getInstance().getBean(ImMessageDao.class);

    public void doPullFeedbackBusiness(String userId, List<FeedbackItem> feedbackItems) throws Exception {
        if (feedbackItems.size() < 1) return;

        List<ImFeedback> imCollectList = feedbackItems.stream().map(cinfo->toFeedback(userId, cinfo)).collect(Collectors.toList());

        saveOrUpdate(userId, imCollectList);
    }

    public void doFeedbackCreateBusiness(String userId, FeedbackCreateReq feedbackCreateReq) throws Exception {
        ImFeedback feedback = toFeedback(userId, feedbackCreateReq);

        saveOrUpdate(userId, Arrays.asList(feedback));
    }



    /**
     * 迁移需要收藏消息中的附件
     * @param imMessage
     */
    public boolean collectMoveMessageAttachFile(String userId, ImMessage imMessage) throws Exception {
        if (!imMessage.isAttachFile()) return false;
        boolean isChange = false;
        String root = ConfigUtil.getRoot();
        LocalDateTime now = LocalDateTime.now();
        String collectDir = ConfigUtil.buildFileDir("collect", DateUtil.toDate(now), userId);
        if (Files.notExists(Paths.get(root + collectDir))) {
            Files.createDirectories(Paths.get(root + collectDir));
        }
        MessageExt messageExt = imMessage.getMessageExt();
        if (!messageExt.getFileUrl().contains("collect")) { // 未迁移
            if (messageExt.getRemote()) {
                String fromFile = root + messageExt.getFileUrl();
                String toFile = root + collectDir + File.separator + messageExt.getFileName();
                Files.move(Paths.get(fromFile), Paths.get(toFile));

                messageExt.setFileUrl(collectDir + File.separator + messageExt.getFileName());
                imMessage.setContent(collectDir + File.separator + messageExt.getFileName());
                imMessage.setMessageExt(messageExt);
                imMessage.initExt();
                imMessage.setUpdateDateTime(new Date());
                messageDao.update(imMessage);

                isChange = true;
            }
        }

        if (imMessage.isRef()) {
            String[] serverIds = imMessage.getRefMessageIds().split(",");
            List<ImMessage> imMessageList = messageDao.getByServerIdsAndUserId(Arrays.stream(serverIds).collect(Collectors.toSet()), userId);
            imMessage.setRefMessages(imMessageList);
            for (ImMessage message : imMessageList) {
                boolean isRefChange = collectMoveMessageAttachFile(userId, message);
                if (!isChange) isChange = isRefChange;
            }
        }
        return isChange;
    }

    private void saveOrUpdate(String userId, List<ImFeedback> imFeedbackList) throws Exception {
        Set<ImFeedback> insertImFeedbackSet = new LinkedHashSet<>();
        Set<ImFeedback> updateImFeedbackSet = new LinkedHashSet<>();

        for(ImFeedback imFeedback : imFeedbackList) {
            ImFeedback dbFeedback = feedbackDao.getByTitle(userId, imFeedback.getTitle());
            if (dbFeedback == null) {
                insertImFeedbackSet.add(imFeedback);
            } else {
                imFeedback.setId(dbFeedback.getId());
                updateImFeedbackSet.add(imFeedback);
            }
        }
        if (insertImFeedbackSet.size() > 0) {
            feedbackDao.batchInsert(insertImFeedbackSet.stream().collect(Collectors.toList()));
        }
        if (updateImFeedbackSet.size() > 0) {
            feedbackDao.batchUpdate(updateImFeedbackSet.stream().collect(Collectors.toList()));
        }

    }

    private ImFeedback toFeedback(String userId, FeedbackItem feedbackItem) {
        ImFeedback feedback = new ImFeedback();
        feedback.setCurrentUserId(userId);
        feedback.setContent(feedbackItem.getContent());
        feedback.setTitle(feedbackItem.getTitle());
        feedback.setServerId(feedbackItem.getServerId());
        feedback.setStatus(ImFeedbackStatus.valueOf(feedbackItem.getStatus().name()));
        feedback.setResult(feedbackItem.getResult());

        return feedback;
    }

    private ImFeedback toFeedback(String userId, FeedbackCreateReq feedbackCreateReq) {
        ImFeedback feedback = new ImFeedback();
        feedback.setCurrentUserId(userId);
        feedback.setContent(feedbackCreateReq.getContent());
        feedback.setTitle(feedbackCreateReq.getTitle());
        feedback.setServerId(feedbackCreateReq.getLocalSeq());
        feedback.setStatus(ImFeedbackStatus.valueOf(feedbackCreateReq.getStatus().name()));
        feedback.setResult(feedbackCreateReq.getResult());

        return feedback;
    }
}
